import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.state.user.profile) {
        await store.dispatch('user/getProfile')
        const routes = await store.dispatch('permission/filterRoutes')
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }
        ])
        next(to.path)
        return
      }
      next()
    }
  } else {
    const whiteList = ['/login', '/404']

    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
